/// <reference path="Math/MathHelper.ts" />
/// <reference path="Utilities/Helper.ts" />
/// <reference path="Units/RectangleUnit.ts" />
/// <reference path="Utilities/Keys.ts" />
/// <reference path="webgl.d.ts" />
/// <reference path="Math/Vector3.ts" />
var canvas: HTMLCanvasElement;
var context: CanvasRenderingContext2D;
var units: ew.Unit[];
var shouldStop = false;
var MathHelper = ew.MathHelper;
window.onload = function () {
    canvas = <HTMLCanvasElement> document.getElementById("awsmness");
    context = canvas.getContext("2d");
    var settings = {
        updateTime: 1000 / 30,

    }

    units = [];

    var boredom = function () {
        var size = 40;
        var unit = new ew.RectangleUnit(
                new ew.Rectangle(MathHelper.randomInInterval(0, canvas.width - size), MathHelper.randomInInterval(0, canvas.height - size), 
                Math.random() * size, Math.random() * size),
                ew.Helper.generateRandomColor());
        var speed = 1;
        unit.velocity = new ew.Vector2(MathHelper.randomInInterval(speed), MathHelper.randomInInterval(speed));
        unit.acceleration = new ew.Vector2(MathHelper.randomInInterval(speed), MathHelper.randomInInterval(speed));
        unit.rotation = MathHelper.randomInInterval(MathHelper.PiOver2)
        unit.rotationSpeed = MathHelper.randomInInterval(MathHelper.toRadians(5));
        units.push(unit);

        //setTimeout(boredom, 10);
    }
    window.addEventListener("keydown", function (args: any) {
        if (args.keyCode == ew.Keys.G)
            boredom();
    }, false);

    var update = function () {

        for (var i in units) {
            units[i].update();
        }
        
        for (var i in units) {
            var unit = units[i];
            if (unit.position.x <= 0 || (unit.position.x + unit.area.width) >= canvas.width) {
                unit.velocity.x = -unit.velocity.x;
                unit.acceleration.x = 0;
            }
            if (unit.position.y <= 0 || (unit.position.y + unit.area.height) >= canvas.height) {
                unit.velocity.y = -unit.velocity.y;
                unit.acceleration.y = 0;
                console.log(unit.position.y);
            }
        }

        if (!shouldStop)
            setTimeout(update, settings.updateTime);
    }

    var draw = function () {
        context.clearRect(0, 0, canvas.width, canvas.height);

        for (var i in units) {
            units[i].draw(context);
        }

        if (!shouldStop)
            requestAnimationFrame(draw);
    }

    update();
    draw();
};